import React, { useEffect, useState } from 'react'
import { Checkbox, Form, message, Modal, Spin, Typography } from 'antd'
import useGetTableData from '@/hooks/useGetTableDataV2'
import { getProduceSchedule, getReserveInvoiceWithPurchase, updatePreloadQty } from '@/api/purchase'
import { countArrivalTracking, exportArrivalTrackingExcel, getArrivalTrackingList } from '@/api/monitor'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useBoxMarkColumns, useTimeColumn } from './TableColumns'
import { PageDataBoxLabelVO, ITableData } from './types'
import CustomTable from '@/components/CustomTable'
import { useNavigate } from 'react-router-dom'
import { UploadOutlined } from '@ant-design/icons'
import { getProductClassConfigByType, getSpuOptions } from '@/api/goods'
import PermissionButton from '@/components/PermissionButton'
import { useAppSelector } from '@/store/hooks'
import { searchConfig, useFormExport } from './FormConfig'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import useSearchUser from '@/hooks/useSearchUser'
import useSearchColor from '@/hooks/useSearchColor'
import { exportNotification, getRecentMonths } from '@/utils/util'
import './index.less'
import useModal from '@/hooks/useModal'
import { EditFormVertical } from '@/components/CustomForm'
import { useArrivalColumns } from '@/pages/Purchase/Order/columns'
import useCachePage from '@/hooks/useCachePage'
import dayjs from 'dayjs'
const Index: React.FC = () => {
  let SpuTimeout: ITimeoutType
  const navigate = useNavigate()
  const [form] = useForm()
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  const [selectKeys, setselectKeys] = useState<React.Key[]>([])
  const [selectInfos, setselectInfos] = useState<PageDataBoxLabelVO[]>([])
  const [tableData, settableData] = useState<ITableData[]>([])
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const { SupplierOption, setSupplierOption, handleSearchSupplier } = useSearchSupplier('supplierId')
  const [expandedRowKeys, setexpandedRowKeys] = useState<React.Key[]>([])
  const { UserOptions, setUserOptions, handleSearchUser } = useSearchUser()
  const { ColorOptions, setColorOptions, handleSearchColor } = useSearchColor()
  const defaultDateRange = getRecentMonths('YYYY-MM-DD')
  const [expand, setexpand] = useState(false)
  const [spinning, setspinning] = useState(false)
  const [CountNum, setCountNum] = useState<{
    willTimeoutNum: number
    timeoutNotArriveNum: number
    timeoutArriveNum: number
  }>({
    willTimeoutNum: 0,
    timeoutNotArriveNum: 0,
    timeoutArriveNum: 0,
  })
  const { setCachePage, getCachePage } = useCachePage()
  const OrderStatus = Form.useWatch('statuses', form)
  const TrackingModal = useModal()
  const TrackingArrivedModal = useModal()
  const TrackingExportModal = useModal({
    onSuccess: async (res) => {
      if (res?.code === 200 && res?.data) {
        await exportNotification(res?.data, navigate).finally(() => setspinning(false))
      }
    },
  })
  const { tableProps, params, search, reset, reload } = useGetTableData<ITableData>(getArrivalTrackingList, {
    form: form,
    immediatelySend: false,
    defaultFieldsParams: {
      officialOrderTimeStart: defaultDateRange,
    },
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
    paramsCallback: (reqParams) => {
      return {
        ...reqParams,
        officialOrderTimeStart:
          reqParams.officialOrderTimeStart && reqParams.officialOrderTimeStart.length === 2
            ? reqParams.officialOrderTimeStart[0]
            : null,
        officialOrderTimeEnd:
          reqParams.officialOrderTimeStart && reqParams.officialOrderTimeStart.length === 2
            ? reqParams.officialOrderTimeStart[1]
            : null,
        requiredArrivalTimeStart:
          reqParams.requiredArrivalTimeStart && reqParams.requiredArrivalTimeStart.length === 2
            ? reqParams.requiredArrivalTimeStart[0]
            : null,
        requiredArrivalTimeEnd:
          reqParams.requiredArrivalTimeStart && reqParams.requiredArrivalTimeStart.length === 2
            ? reqParams.requiredArrivalTimeStart[1]
            : null,
        onlySeeProduceScheduleExp: reqParams?.selectKey?.includes('onlySeeProduceScheduleExp') ? 1 : 0,
        onlySeeQcExp: reqParams?.selectKey?.includes('onlySeeQcExp') ? 1 : 0,
        statuses: reqParams.statuses ? (reqParams.statuses === '#' ? [3, 5] : [reqParams.statuses]) : null,
        selectKey: null,
      }
    },
  })
  useEffect(() => {
    getProductClassConfig()
    handleCacheData()
    getcontractTodo()
  }, [])
  useEffect(() => {
    settableData(tableProps.dataSource)
    if (expand) {
      const ids = tableProps?.dataSource?.map((item) => item?.seqId)
      setexpandedRowKeys(ids)
    } else {
      setexpandedRowKeys([])
    }
  }, [tableProps.dataSource, expand])
  const getcontractTodo = async () => {
    const res = await countArrivalTracking()
    if (res.code == 200) {
      setCountNum(res?.data)
    } else {
      setCountNum({
        willTimeoutNum: 0,
        timeoutNotArriveNum: 0,
        timeoutArriveNum: 0,
      })
    }
  }
  const handleCacheData = async () => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      await form.validateFields()
      search()
      setCachePage({ ...params })
    } else {
      form.setFieldsValue({
        ...cacheData,
      })
      setSpuOptions(cacheData?.SpuOptions || [])
      setSupplierOption(cacheData?.SupplierOption || [])
      setUserOptions(cacheData?.UserOptions || [])
      setColorOptions(cacheData?.ColorOptions || [])
      const { SpuOptions, SupplierOption, UserOptions, ColorOptions, ...resetCacheData } = cacheData
      reload({ ...resetCacheData })
    }
  }
  const selectRows = (keys: React.Key[], info: PageDataBoxLabelVO[]) => {
    setselectKeys(keys)
    setselectInfos(info)
  }
  const handleSearchSpuOptions = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSpuOptions<{
        spuName: string
        spuCode: string
        designCode: string
      }>({ keyword: newValue })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: `${item?.spuCode}｜${item.spuName}${item?.designCode ? '｜' + item?.designCode : ''}`,
              value: item.spuCode,
            }
          }) || []
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId,
          isLeaf: false,
        }
      }) || []
    setclassBig(classIdOptions)
  }
  const onSave = async (tableData: ITableData) => {
    const res = await updatePreloadQty({
      boxLabelCode: tableData.boxLabelCode,
      preloadQty: tableData.preloadQty,
    }).finally(() => reload())
    if (res.code === 200) {
      message.success('操作成功，修改数量后记得重新打印箱唛～')
    }
  }
  const onView = async (info: ITableData) => {
    const res = await getProduceSchedule({ purchaseOrderCode: info?.purchaseOrderCode })
    if (res.code === 200) {
      const data = (res?.data || []).filter((item: any) => item?.colorDetailName === info.colorDetailName)
      TrackingModal.openModal(data)
    }
  }
  const onViewArrived = async (info: ITableData) => {
    const res = await getReserveInvoiceWithPurchase({
      purchaseOrderCode: info?.purchaseOrderCode,
      id: info?.purchaseOrderId,
      spuCode: info.commoditySkus && info.commoditySkus.length > 0 ? info?.spuCode : null,
      colorDetailName: info.commoditySkus && info.commoditySkus.length > 0 ? info?.colorDetailName : null,
      skuCode: info.commoditySkus && info.commoditySkus.length > 0 ? null : info?.skuCode,
    })
    if (res.code === 200) {
      TrackingArrivedModal.openModal(res?.data || [])
    }
  }
  return (
    <PageContainer className="monitor_goodstracking_wrap">
      <div className="waittodo_box">
        <div className="wait_main">
          <div className="wm_item">
            <div className="wm_item_title">即将超时</div>
            <div className="wm_item_num">
              <Typography.Link
                underline
                onClick={() => {
                  form.resetFields()
                  form.setFieldsValue({
                    arrivalWarningStatues: [1],
                    officialOrderTimeStart: [
                      dayjs().subtract(6, 'month').format('YYYY-MM-DD'),
                      dayjs().add(6, 'month').format('YYYY-MM-DD'),
                    ],
                  })
                  search()
                }}
              >
                {CountNum.willTimeoutNum || 0}条
              </Typography.Link>
            </div>
          </div>
          <div className="wm_item">
            <div className="wm_item_title">超时未到货</div>
            <div className="wm_item_num">
              <Typography.Link
                underline
                onClick={() => {
                  form.resetFields()
                  form.setFieldsValue({
                    arrivalWarningStatues: [2],
                    officialOrderTimeStart: [
                      dayjs().subtract(6, 'month').format('YYYY-MM-DD'),
                      dayjs().add(6, 'month').format('YYYY-MM-DD'),
                    ],
                  })
                  search()
                }}
              >
                {CountNum.timeoutNotArriveNum || 0}条
              </Typography.Link>
            </div>
          </div>
          {/* <div className="wm_item">
            <div className="wm_item_title">超时到货</div>
            <div className="wm_item_num">
              <Typography.Link
                underline
                onClick={() => {
                  form.resetFields()
                  form.setFieldsValue({
                    arrivalWarningStatues: [3],
                  })
                  search()
                }}
              >
                {CountNum.timeoutArriveNum || 0}条
              </Typography.Link>
            </div>
          </div> */}
        </div>
      </div>
      <SearchForm
        params={params}
        form={form}
        searchConfig={searchConfig({
          SpuOptions,
          handleSearchSpuOptions,
          SupplierOption,
          handleSearchSupplier,
          classBig,
          UserOptions,
          handleSearchUser,
          ColorOptions,
          handleSearchColor,
          form,
        })}
        onFinish={async () => {
          setselectKeys([])
          setselectInfos([])
          await form.validateFields()
          search()
          setCachePage({
            ...form.getFieldsValue(),
            SpuOptions,
            SupplierOption,
            UserOptions,
            ColorOptions,
            // 只要search那么current肯定是1 current肯定是1
            current: 1,
            size: params.size,
          })
        }}
        onReset={() => {
          setselectKeys([])
          setselectInfos([])
          reset()
          setCachePage({ current: 1, size: 10, officialOrderTimeStart: defaultDateRange })
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <Form form={form} className="suggestion_form" initialValues={{ selectParams: 'style' }}>
                <Form.Item noStyle name="selectKey">
                  <Checkbox.Group
                    onChange={(selectKey) => {
                      form.setFieldValue('statuses', 2)
                      const cacheData = getCachePage()
                      setCachePage({
                        ...cacheData,
                        statuses: 2,
                        selectKey,
                        // 只要search那么current肯定是1 current肯定是1
                        current: 1,
                      })
                      search()
                    }}
                    options={[
                      {
                        label: '只看生产进度异常',
                        value: 'onlySeeProduceScheduleExp',
                        disabled: OrderStatus === '#',
                      },
                      {
                        label: '只看未执行尾查',
                        value: 'onlySeeQcExp',
                        disabled: OrderStatus === '#',
                      },
                    ]}
                  />
                </Form.Item>
              </Form>
              <Checkbox.Group
                onChange={(vals) => {
                  const expand = !!vals?.includes('size')
                  setexpand(expand)
                }}
                options={[
                  {
                    label: '展开到尺码',
                    value: 'size',
                  },
                ]}
              />
            </div>
            <div className="table_extra_flex">
              <PermissionButton
                permission="goodstrackingExport"
                icon={<UploadOutlined />}
                loading={TrackingExportModal.confirmLoading}
                onClick={() => {
                  TrackingExportModal.openModal()
                }}
              >
                导出
              </PermissionButton>
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        className="small_sise_customtable"
        bordered
        columns={useBoxMarkColumns({
          navigate,
          tableData,
          settableData,
          onSave,
          onView,
          onViewArrived,
          reloadPgae: reload,
        })}
        {...tableProps}
        rowKey={(rows) => rows.seqId}
        selectRows={selectRows}
        selectedRowKeys={selectKeys}
        tableRowGray={() => 'fkjsooo'}
        isScrollY
        extraHeight={70}
        expandable={{
          childrenColumnName: 'commoditySkus',
          expandedRowKeys,
          onExpandedRowsChange: (keys: React.Key[]) => {
            setexpandedRowKeys(keys)
          },
        }}
      />
      <Modal
        title="生产时间跟踪"
        footer={null}
        open={TrackingModal.open}
        maskClosable
        onCancel={TrackingModal.closeModal}
        width={1200}
      >
        <CustomTable
          bordered
          columns={useTimeColumn()}
          dataSource={TrackingModal?.currentRecord || []}
          pagination={null}
          rowKey={(rows) => rows?.id}
        />
      </Modal>
      <Modal
        title="到货批次"
        footer={null}
        open={TrackingArrivedModal.open}
        maskClosable
        onCancel={TrackingArrivedModal.closeModal}
        width={1200}
        wrapClassName="tracking_modal_self_wrap"
      >
        <CustomTable
          bordered
          columns={useArrivalColumns()}
          dataSource={TrackingArrivedModal?.currentRecord || []}
          pagination={null}
          rowKey={(rows) => rows?.reserveInvoiceCode}
          scroll={{ x: 1000 }}
        />
      </Modal>
      <Modal
        title="导出选项"
        maskClosable
        open={TrackingExportModal.open}
        onCancel={TrackingExportModal.closeModal}
        okText="导出"
        onOk={() => {
          setspinning(true)
          TrackingExportModal.handleSubmit((vals) =>
            exportArrivalTrackingExcel({
              ...params,
              exportSkc: vals?.exportDataTypeList?.includes('exportSkc') ? 1 : 0,
              exportSku: vals?.exportDataTypeList?.includes('exportSku') ? 1 : 0,
              exportDataTypeList: null,
            }),
          )
        }}
        confirmLoading={TrackingExportModal.confirmLoading}
      >
        <EditFormVertical
          editConfig={useFormExport()}
          form={TrackingExportModal.form}
          initialValues={{
            exportDataTypeList: ['exportSkc', 'exportSku'],
          }}
        />
      </Modal>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
